<template>
  <div>
    <el-upload
      ref="upload"
      :limit="1"
      accept=".jpg,.jpeg,.gif,.png,.webp,.bmp,.ico,.svg"
      :action="upload.url"
      :headers="upload.headers"
      :file-list="upload.fileList"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :before-upload="beforeUpload"
    >
      <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
      <div slot="tip" class="el-upload__tip">{{tips}}</div>
    </el-upload>
    <el-image
      v-if="cover !== undefined  && cover !== null"
      :src="cover"
      style="width: 400px; height: 200px"
    ></el-image>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'CoverUpload',
  props: {
    /* 图片路径 */
    value: {
      type: String,
      default: "",
    },
    tips: {
      type: String,
      default: "",
    }
  },
  watch:{
    value: {
      handler(newV){
        this.cover = newV
        this.upload.fileList = []
      },
      immediate: true
    }
  },
  data() {
    return {
      cover: this.value,
      // 图片上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        // 上传的文件列表
        fileList: []
      },
    }
  },
  methods: {
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      this.cover = response.url
      this.$emit("coverSuccess",this.cover)
      this.$modal.msgSuccess(response.msg);
    },
    // 文件上传前处理
    beforeUpload(file) {
      const isLt = file.size / 1024 / 1024 < 800
      if (!isLt) {
        this.$message({
          message: '上传文件大小不能超过 800MB!',
          type: 'warning'
        })
      }
      return isLt
    }
  }
}
</script>
